package com.opencv;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;

/**
 * @Author: hanll
 * @ClassName: OpenCV
 * @Date: 2022-11-04 10:11
 * @Version: 1.0
 * @Description:
 */
public class OpenCV {

    static {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

    public static void main(String[] args) {
        //分类器文档地址
        CascadeClassifier faceDetector = new CascadeClassifier("D:\\Dev\\opencv\\opencv\\sources\\data\\lbpcascades\\lbpcascade_frontalface.xml");
        if(faceDetector.empty()){
            System.out.println("读取配置文件失败");
            return;
        }
        //识别的文档地址
        Mat image = Imgcodecs.imread("D:\\opencvtest\\1.jpg");
        // Detect faces in the image.
        // MatOfRect is a special container class for Rect.
        MatOfRect faceDetections = new MatOfRect();
        faceDetector.detectMultiScale(image, faceDetections);
        System.out.println(String.format("匹配到 %s 张人脸", faceDetections.toArray().length));
        // Draw a bounding box around each face.
        for (Rect rect : faceDetections.toArray()) {
            Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
        }
        //识别后文档地址
        String filename = "D:\\opencvtest\\faceDetection.png";
        boolean isok = Imgcodecs.imwrite(filename, image);
        if (isok) {
            System.out.println(String.format("识别成功文件已写入： %s", filename));
        } else {
            System.out.println("识别未是张人脸图片");
        }
    }
}
